'use strict';

import * as betterBody from 'koa-better-body';
import * as convert from 'koa-convert';
import * as Json from 'koa-json';
import * as kcors from 'kcors';
import * as Koa from 'koa';
import * as serve from 'koa-static';
import * as path from 'path';
import * as mongodb from './middleware/mongodb';
import config from './middleware/config';
import koaError from './middleware/error';
import logger from './middleware/logger';
import { verification, verificationUrl } from './middleware/token';
import { Route } from './middleware/controller';
import { timeout } from './middleware/timeout';
import { KLENUM } from './kalend';

const app = new Koa()
// 跨域
app.use(kcors({ credentials: true, exposeHeaders: ['token', 'Content-Disposition'] }));
app.use(Json());
app.use(koaError);

app.use(serve(path.resolve(__dirname, "apidoc")));
app.use(convert(betterBody({
    fields: "body",
    formLimit: "50mb",//限制提交文件的最大值
    jsonLimit: "50mb",
    textLimit: "50mb"
})));

if (config.enabledToken) {
    //Token验证
    app.use(verification);
}

if (config.enabledUrl) {
    //URL验证
    app.use(verificationUrl);
}

//超时验证 请求超过20秒未响应 算请求超时
app.use(timeout(20 * 1000));
{
    var mongoConnection = config.get('mongo');
    let envstr = "development";//获取node_env参数 默认为开发模式
    // 连接MongoDB
    const connection = mongodb.init(mongoConnection[envstr.trim()]);//必须去除空格 当前默认配置中的就是用空格的
}

// 注册路由
const router = new Route(app);
router.registerRouters(`${__dirname}/controller`);
KLENUM.register()




// 处理错误
app.on('error', (err: any, ctx: Koa.Context) => {
    logger(ctx).fatal(err);
});

// 启动服务
app.listen(config.get('port'), () => {
    /** 自动获取热线反馈信息 1小时一次 */
    // if (config.get('autoHotLine')) {
    //     var rule = new schedule.RecurrenceRule();
    //     //每1小时执行一次
    //     rule.minute = 60; rule.second = 0;
    //     schedule.scheduleJob(rule, function () {
    //         let result = hotlinestatisticsService.refresh();
    //         console.log("热线反馈同步成功" + Date.now().toLocaleString());
    //     });
    // }

    console.log(`API 服务启动，监听 ${config.get('port')} 端口`);
});